package com.hethongviet.vendingmobi.helpers;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.hethongviet.library.common.Utils;
import com.hethongviet.library.model.Model;
import com.hethongviet.library.model.Transaction;
import com.hethongviet.library.network.ConstantNetwork.JSON;
import com.hethongviet.library.network.OnNetworkHandleListener;
import com.hethongviet.vendingmobi.Constants;
import com.hethongviet.vendingmobi.model.Account;

public class Network
{

	private static final String CONTENT_TYPE = "application/json";

	private static OnNetworkHandleListener onNetworkHandleListener = null;

	private static Transaction transaction = null;

	public static void send(final String method, final String messageOut)
	{
		new Thread(new Runnable()
		{

			@Override
			public void run()
			{
				// Create a new HttpClient and Post Header

				HttpParams myParams = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(myParams, 10000);
				HttpConnectionParams.setSoTimeout(myParams, 10000);
				HttpClient httpclient = new DefaultHttpClient();

				try
				{
					HttpPost httppost = new HttpPost(
							com.hethongviet.vendingmobi.Constants.SERVER_URL
									+ method + ".php");
					httppost.setHeader("Content-type", CONTENT_TYPE);
					StringEntity se = new StringEntity(messageOut);
					se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
							CONTENT_TYPE));
					httppost.setEntity(se);

					HttpResponse response = httpclient.execute(httppost);
					String responseString = EntityUtils.toString(response
							.getEntity());

					responseString = reprocessMessage(responseString);

					Log.i("WEB response", responseString);

					if (transaction != null)
					{
						transaction.setMessageReceived(responseString);
					}

					if (getOnNetworkHandleListener() != null)
					{
						getOnNetworkHandleListener().onNetworkMessageIncomming(
								transaction);
					}
				} catch (Exception e)
				{
					Log.e("WEB Http error", e.toString());

					if (getOnNetworkHandleListener() != null)
					{
						getOnNetworkHandleListener().onConnectFail(
								Constants.CONNECT);
					}
				}
			}
		}).start();

	}

	private static String reprocessMessage(String message)
	{
		String messageTemp = "";

		for (int i = 0; i < message.length(); i++)
		{
			char c = message.charAt(i);

			if (c != '\n' && c != '\r')
			{
				messageTemp += c;
			}
		}

		return messageTemp.trim();
	}

	private static void prepareSend(JSONObject jsonObject, String method,
			Model model)
	{
		/* Send */
		Utils.debug("Sending message = " + jsonObject.toString());
		Network.send(method, jsonObject.toString());

		transaction = new Transaction();
		transaction.setMessageSent(jsonObject.toString());
		transaction.setModel(model);
		transaction.setMethodSent(method);
	}

	public static boolean sendRequestLogin(String machineCode, String username,
			String password)
	{

		JSONObject jsonObject = new JSONObject();
		try
		{
			jsonObject.put(JSON.USERNAME, username);
			jsonObject.put(JSON.PASSWORD, password);
			jsonObject.put(JSON.MACHINE_CODE, machineCode);

		} catch (JSONException e)
		{
			e.printStackTrace();
			return false;
		}

		prepareSend(jsonObject, com.hethongviet.vendingmobi.Constants.LOGIN,
				null);
		return true;
	}

	public static boolean sendRequestAddAccount(Account account, String id,
			String role)
	{

		JSONObject jsonObject = new JSONObject();
		try
		{
			jsonObject.put(JSON.USERNAME, account.getUsername());
			jsonObject.put(JSON.PASSWORD, account.getPassword());
			jsonObject.put(JSON.MACHINE_CODE, account.getName());
			jsonObject.put(JSON.ACCOUNT_ID, id);
			jsonObject.put(JSON.ACCOUNT_ROLE, role);

		} catch (JSONException e)
		{
			e.printStackTrace();
			return false;
		}

		Account newAccount = new Account();
		newAccount.setCellPhone(id);
		newAccount.setRole(role);

		prepareSend(jsonObject,
				com.hethongviet.vendingmobi.Constants.ADD_ACCOUNT, newAccount);
		return true;
	}

	public static boolean sendRequestGetBoxes(Account account)
	{

		JSONObject jsonObject = new JSONObject();
		try
		{
			jsonObject.put(JSON.USERNAME, account.getUsername());
			jsonObject.put(JSON.PASSWORD, account.getPassword());
			jsonObject.put(JSON.MACHINE_CODE, account.getName());

		} catch (JSONException e)
		{
			e.printStackTrace();
			return false;
		}

		prepareSend(jsonObject,
				com.hethongviet.vendingmobi.Constants.GET_BOX_INVENTORY, null);

		return true;
	}

	public static OnNetworkHandleListener getOnNetworkHandleListener()
	{
		return onNetworkHandleListener;
	}

	public static void setOnNetworkHandleListener(
			OnNetworkHandleListener onNetworkHandleListener)
	{
		Network.onNetworkHandleListener = onNetworkHandleListener;
	}

	public Transaction getTransaction()
	{
		return transaction;
	}

	public void setTransaction(Transaction transaction)
	{
		Network.transaction = transaction;
	}
}
